package com.qilu.pe.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.EventModel;
import com.qilu.pe.dao.bean.ItemSet;
import com.qilu.pe.dao.bean.ItemType;
import com.qilu.pe.dao.bean.OrderDate;
import com.qilu.pe.dao.bean.Patient;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.ui.activity.ChoosePatientActivity;
import com.qilu.pe.ui.activity.ConfirmPlaceOrderInfoActivity;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.zyyoona7.popup.EasyPopup;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 预约下单--信息录入
public class PlaceOrder1Fragment extends BaseFragment {
    private RecyclerView rcv_date, rcv_item_selected, rcv_set_selected;// 日期列表,选择的项目,选择的套餐
    private RelativeLayout rl_sel_patient;// 选择病人
    // 病人，一键全选，按照名称，按照分类，按照套餐，我的收藏
    private TextView tv_patient, tv_one_all, tv_item_name, tv_item_category, tv_item_set, tv_item_collect;
    private TextView tv_price, tv_ok;// 价格 去支付
    private TextView tv_query, tv_reset, tv_confirm;// 按项目名称查询,重置,确认
    private RecyclerView rcv_query_item;// 查询的项目列表
    private AppCompatEditText et_search;// 输入搜索的关键字
    private TextView tv_content;// 点击项目的圆形叹号弹出说明框的文字

    private String searchName;// 输入搜索的关键字

    private List<OrderDate> dateList = new ArrayList<>();
    private DateListAdapter adapter;

    private List<ItemSet> itemSetList = new ArrayList<>();// 选择的项目列表
    private SelectedItemListAdapter itemAdapter;// 选择的项目adapter

    private List<ItemSet> setList = new ArrayList<>();// 选择的套餐列表
    private SelectedItemListAdapter setAdapter;// 选择的套餐adapter

    private List<ItemSet> queryItemList = new ArrayList<>();
    private QueryItemListAdapter queryItemAdapter;

    private List<ItemSet> querySetList = new ArrayList<>();
    private QueryItemListAdapter querySetAdapter;

    private List<ItemType> itemTypeList = new ArrayList<>();// 项目类型列表
    private ItemTypeAdapter itemTypeAdapter;

    private List<ItemSet> itemByTypeList = new ArrayList<>();// 根据项目分类获取项目列表(点击项目分类展示项目列表)
    ItemByTypeListAdapter itemByTypeAdapter;

    private List<ItemSet> collectItemList = new ArrayList<>();// 收藏的项目列表
    private CollectItemListAdapter collectItemAdapter;

    private EasyPopup mCirclePop;

    private Patient currPatient;// 选择的患者
    private OrderDate currOrderData;// 当前选择的预约时间

    public PlaceOrder1Fragment() {

    }

    public static PlaceOrder1Fragment newInstance(String status, Patient patient) {
        PlaceOrder1Fragment fragment = new PlaceOrder1Fragment();
        Bundle args = new Bundle();
        if (null != patient) {
            args.putSerializable("patient", patient);// 患者页面-立即预约-传过来的患者对象
        }
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Arad.bus.register(this);
        Patient patient = (Patient) getArguments().getSerializable("patient");
        if (null != patient) {
            currPatient = patient;
        }
        adapter = new DateListAdapter(getActivity());
        itemAdapter = new SelectedItemListAdapter(getActivity());
        setAdapter = new SelectedItemListAdapter(getActivity());
        setAdapter.TYPE = 2;
        itemTypeAdapter = new ItemTypeAdapter(getActivity());
        itemByTypeAdapter = new ItemByTypeListAdapter(getActivity());
        collectItemAdapter = new CollectItemListAdapter(getActivity());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)// EventBus事件接收方法
    public void eventMsg(EventModel ev) {
        if (ev.getEventCode() == 20092351) {
            currPatient = (Patient) ev.getEventObj();
            tv_patient.setText(currPatient.getName() + "        " + currPatient.getPhone());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_place_order1, container, false);
        rcv_date = v.findViewById(R.id.rcv_date);
        rcv_item_selected = v.findViewById(R.id.rcv_item_selected);
        rcv_set_selected = v.findViewById(R.id.rcv_set_selected);
        rl_sel_patient = v.findViewById(R.id.rl_sel_patient);
        tv_patient = v.findViewById(R.id.tv_patient);
        tv_one_all = v.findViewById(R.id.tv_one_all);
        tv_item_name = v.findViewById(R.id.tv_item_name);
        tv_item_category = v.findViewById(R.id.tv_item_category);
        tv_item_set = v.findViewById(R.id.tv_item_set);
        tv_item_collect = v.findViewById(R.id.tv_item_collect);
        tv_price = v.findViewById(R.id.tv_price);
        tv_ok = v.findViewById(R.id.tv_ok);
        tv_query = v.findViewById(R.id.tv_query);

        if (null != currPatient) {
            tv_patient.setText(currPatient.getName() + "        " + currPatient.getPhone());
        }

        // 预约时间列表
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(RecyclerView.HORIZONTAL);
        rcv_date.setLayoutManager(manager);
        rcv_date.setAdapter(adapter);
        // 选择项目列表
        LinearLayoutManager manager2 = new LinearLayoutManager(getActivity());
        rcv_item_selected.setLayoutManager(manager2);
        rcv_item_selected.setAdapter(itemAdapter);

        LinearLayoutManager manager3 = new LinearLayoutManager(getActivity());
        rcv_set_selected.setLayoutManager(manager3);
        rcv_set_selected.setAdapter(setAdapter);

        reqDatelList();// 接口获取预约时间
//        genDateList();// 自己生成三天预约时间

        setListeners();

        alert = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();
        alert2 = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();
        alert3 = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();
        alert4 = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();

        mCirclePop = EasyPopup.create()
                .setContentView(getActivity(), R.layout.layout_pop_item_tips)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                .apply();
        tv_content = mCirclePop.findViewById(R.id.tv_content);

        return v;
    }

    private void genDateList() {
        String f = "yyyy-MM-dd";
        SimpleDateFormat format = new SimpleDateFormat(f);
        Long todayMill = new Date().getTime();
        Long oneDay = 1000 * 60 * 60 * 24L;

        OrderDate today = new OrderDate("今天", format.format(todayMill));
        OrderDate tomorrow = new OrderDate("明天", format.format(todayMill + oneDay));
        OrderDate after = new OrderDate("后天", format.format(todayMill + oneDay * 2));

        today.setSelect(true);
        currOrderData = today;

        dateList.add(today);
        dateList.add(tomorrow);
        dateList.add(after);

        adapter.setDataList(dateList);
    }

    private void setListeners() {
        setOnClickListener(rl_sel_patient, tv_one_all, tv_item_name, tv_item_category, tv_item_set,
                tv_item_collect, tv_ok);
    }

    @Override
    public void onClick(View v) {
        if (v == rl_sel_patient) {// 选择病人
            startActivity(ChoosePatientActivity.class);
        }
        if (v == tv_one_all) {
            hideProgress();
            reqComItem();
            showProgress();
        }
        if (v == tv_item_name) {// 按项目名称检索
            showDialog();
        }
        if (v == tv_item_category) {// 按项目分类检索
            showDialog2();
        }
        if (v == tv_item_set) {// 套餐检索
            showDialog3();
        }
        if (v == tv_item_collect) {// 选择收藏项目
            showDialog4();
        }
        if (v == tv_ok) {// 去支付
            if (verifyInfo()) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("patient", currPatient);
                if (dateList.size() >= 1) {
//                    bundle.putString("orderTime", currOrderData.getTimeStrCn() + ":" + currOrderData.getTimeStr());
                    bundle.putString("orderTime", currOrderData.getScalar());
                } else {
                    bundle.putString("orderTime", "今天:" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                }
                bundle.putSerializable("itemList", (Serializable) itemSetList);
                bundle.putSerializable("setList", (Serializable) setList);
//                bundle.putString("time", currOrderData.getTimeStr());
                bundle.putString("time", currOrderData.getScalar());
                startActivity(ConfirmPlaceOrderInfoActivity.class, bundle);
            }
        }
    }

    private AlertDialog alert4;// 弹窗
    private View alert_view4;

    public void showDialog4() {// 弹窗界面
        alert4.show();
        alert_view4 = View.inflate(getActivity(), R.layout.layout_alert_collect_item_list, null);
        tv_reset = alert_view4.findViewById(R.id.tv_reset);
        tv_confirm = alert_view4.findViewById(R.id.tv_confirm);
        rcv_query_item = alert_view4.findViewById(R.id.rcv_query_item);

        TextView tv_title = alert_view4.findViewById(R.id.tv_title);
        tv_title.setText("选择收藏项目");

        // 弹出窗口以后先请求收藏项目列表数据
        hideProgress();
        reqCollect();
        showProgress();

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        collectItemAdapter = new CollectItemListAdapter(getActivity());
        rcv_query_item.setLayoutManager(manager);
        rcv_query_item.setAdapter(collectItemAdapter);
        tv_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isDataEmpty(collectItemList)) {
                    for (int i = 0; i < collectItemList.size(); i++) {
                        collectItemList.get(i).setSelect(false);
                    }
                    collectItemAdapter.setDataList(collectItemList);
                }
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 0; i < collectItemList.size(); i++) {
                    ItemSet item = collectItemList.get(i);
                    if (TextUtils.equals("0", item.getType())) {// 0 项目 1 套餐
                        if (item.isSelect()) {
                            String name = item.getName();
                            boolean isExist = false;// 是否已经存在
                            for (int j = 0; j < itemSetList.size(); j++) {// 遍历已经选择的项目,判断是否已经存在
                                if (TextUtils.equals(name, itemSetList.get(j).getName())) {
                                    isExist = true;
                                }
                            }
                            if (!isExist) {// 已经选择的列表不存在已经选中的,择加入到选择列表中
                                itemSetList.add(item);
                            }
                        }
                    } else {// 套餐
                        if (item.isSelect()) {
                            String name = item.getName();
                            boolean isExist = false;// 是否已经存在
                            for (int j = 0; j < setList.size(); j++) {// 遍历已经选择的套餐,判断是否已经存在
                                if (TextUtils.equals(name, setList.get(j).getName())) {
                                    isExist = true;
                                }
                            }
                            if (!isExist) {// 已经选择的列表不存在已经选中的,择加入到选择列表中
                                setList.add(item);
                            }
                        }
                    }
                }
                setSelectedItemListAndPrice();
                alert4.dismiss();
            }
        });

        AlertUtil.setAlertRightInStyle(alert4.getWindow(), alert_view4, getActivity());
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(getActivity(), R.layout.layout_alert_search_by_name, null);
        et_search = alert_view.findViewById(R.id.et_search);
        tv_query = alert_view.findViewById(R.id.tv_query);
        tv_reset = alert_view.findViewById(R.id.tv_reset);
        tv_confirm = alert_view.findViewById(R.id.tv_confirm);
        rcv_query_item = alert_view.findViewById(R.id.rcv_query_item);

        TextView tv_title = alert_view.findViewById(R.id.tv_title);
        tv_title.setText("项目名称检索");

        searchName = et_search.getText().toString().trim();

        // 弹出窗口以后先请求一下项目列表数据
        hideProgress();
        reqQueryItem(searchName);
        showProgress();

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        queryItemAdapter = new QueryItemListAdapter(getActivity());
        rcv_query_item.setLayoutManager(manager);
        rcv_query_item.setAdapter(queryItemAdapter);
        tv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchName = et_search.getText().toString().trim();
                // 点击查询请求项目列表数据
                hideProgress();
                reqQueryItem(searchName);
                showProgress();
            }
        });
        tv_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isDataEmpty(queryItemList)) {
                    for (int i = 0; i < queryItemList.size(); i++) {
                        queryItemList.get(i).setSelect(false);
                    }
                    queryItemAdapter.notifyDataSetChanged();
                }
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isSelect = false;
                for (int i = 0; i < queryItemList.size(); i++) {
                    ItemSet item = queryItemList.get(i);
                    if (item.isSelect()) {
                        String name = item.getName();
                        isSelect = true;
                        boolean isExist = false;// 是否已经存在
                        for (int j = 0; j < itemSetList.size(); j++) {// 遍历已经选择的项目,判断是否已经存在
                            if (TextUtils.equals(name, itemSetList.get(j).getName())) {
                                isExist = true;
                            }
                        }
                        if (!isExist) {// 已经选择的列表不存在已经选中的,择加入到选择列表中
                            itemSetList.add(item);
                        }
                    }
                }
                setSelectedItemListAndPrice();
                alert.dismiss();
            }
        });

        AlertUtil.setAlertRightInStyle(alert.getWindow(), alert_view, getActivity());

        alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    private AlertDialog alert2;// 弹窗
    private View alert_view2;

    public void showDialog2() {// 弹窗界面
        alert2.show();
        alert_view2 = View.inflate(getActivity(), R.layout.layout_alert_item_type_list, null);

        // 重置
        alert_view2.findViewById(R.id.tv_reset).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isDataEmpty(itemTypeList)) {
                    for (int i = 0; i < itemTypeList.size(); i++) {
                        itemTypeList.get(i).setSelect(false);
                        itemTypeAdapter.setDataList(itemTypeList);
                    }
                }
            }
        });
        alert_view2.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isSelect = false;
                for (int i = 0; i < itemByTypeList.size(); i++) {
                    ItemSet item = itemByTypeList.get(i);
                    if (item.isSelect()) {
                        String name = item.getName();
                        isSelect = true;
                        boolean isExist = false;// 是否已经存在
                        for (int j = 0; j < itemSetList.size(); j++) {// 遍历已经选择的项目,判断是否已经存在
                            if (TextUtils.equals(name, itemSetList.get(j).getName())) {
                                isExist = true;
                            }
                        }
                        if (!isExist) {// 已经选择的列表不存在已经选中的,择加入到选择列表中
                            itemSetList.add(item);
                        }
                    }
                }
                setSelectedItemListAndPrice();
                alert2.dismiss();
            }
        });

        RecyclerView rcv_item_type = alert_view2.findViewById(R.id.rcv_item_type);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_item_type.setLayoutManager(manager);
        rcv_item_type.setAdapter(itemTypeAdapter);

        hideProgress();
        reqItemTypeList();
        showProgress();

        AlertUtil.setAlertRightInStyle(alert2.getWindow(), alert_view2, getActivity());
    }

    private AlertDialog alert3;// 弹窗
    private View alert_view3;

    public void showDialog3() {// 弹窗界面
        alert3.show();
        alert_view3 = View.inflate(getActivity(), R.layout.layout_alert_search_by_name, null);
        et_search = alert_view3.findViewById(R.id.et_search);
        tv_query = alert_view3.findViewById(R.id.tv_query);
        tv_reset = alert_view3.findViewById(R.id.tv_reset);
        tv_confirm = alert_view3.findViewById(R.id.tv_confirm);
        rcv_query_item = alert_view3.findViewById(R.id.rcv_query_item);

        TextView tv_title = alert_view3.findViewById(R.id.tv_title);
        tv_title.setText("套餐检索");

        searchName = et_search.getText().toString().trim();

        // 弹出窗口以后先请求一下项目列表数据
        hideProgress();
        reqQuerySet(searchName);
        showProgress();

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        querySetAdapter = new QueryItemListAdapter(getActivity());
        querySetAdapter.TYPE = 2;
        rcv_query_item.setLayoutManager(manager);
        rcv_query_item.setAdapter(querySetAdapter);
        tv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchName = et_search.getText().toString().trim();
                // 点击查询请求项目列表数据
                hideProgress();
                reqQuerySet(searchName);
                showProgress();
            }
        });
        tv_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isDataEmpty(querySetList)) {
                    for (int i = 0; i < querySetList.size(); i++) {
                        querySetList.get(i).setSelect(false);
                    }
                    querySetAdapter.notifyDataSetChanged();
                }
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isSelect = false;
                for (int i = 0; i < querySetList.size(); i++) {
                    ItemSet item = querySetList.get(i);
                    if (item.isSelect()) {
                        String name = item.getName();
                        isSelect = true;
                        boolean isExist = false;// 是否已经存在
                        for (int j = 0; j < setList.size(); j++) {// 遍历已经选择的项目,判断是否已经存在
                            if (TextUtils.equals(name, setList.get(j).getName())) {
                                isExist = true;
                            }
                        }
                        if (!isExist) {// 已经选择的列表不存在已经选中的,择加入到选择列表中
                            setList.add(item);
                        }
                    }
                }
                setSelectedItemListAndPrice();
                alert3.dismiss();
            }
        });

        AlertUtil.setAlertRightInStyle(alert3.getWindow(), alert_view3, getActivity());

        alert3.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alert3.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    // 请求收藏的项目
    private Disposable reqCollect() {
        return APIRetrofit.getDefault().reqMyCollectList(Global.HEADER, 1, 999999)
                .compose(RxUtil.<BaseResult2<List<ItemSet>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ItemSet>>>() {
                    @Override
                    public void accept(BaseResult2<List<ItemSet>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            collectItemList = listBaseResult2.getData();
                            if (!isDataEmpty(collectItemList)) {
                                // 由于收藏的项目和套餐id为收藏id,pid为项目或套餐id,所以数据需要处理一下
                                for (int i = 0; i < collectItemList.size(); i++) {
                                    collectItemList.get(i).setId(collectItemList.get(i).getPid());
                                }
                            }
                            collectItemAdapter.setDataList(collectItemList);
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                        if (isDataEmpty(collectItemList)) {
                            ToastUtils.showShort("暂无数据");
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 获取项目分类
    private Disposable reqItemTypeList() {
        return APIRetrofit.getDefault().reqItemTypeList("")
                .compose(RxUtil.<BaseResult2<List<ItemType>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ItemType>>>() {
                    @Override
                    public void accept(BaseResult2<List<ItemType>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            itemTypeList = listBaseResult2.getData();
                            itemTypeAdapter.setDataList(itemTypeList);
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 验证选择信息
    private boolean verifyInfo() {
        if (null == currPatient) {
            ToastUtils.showShort("请选择病人");
            return false;
        }
        if (itemSetList.size() <= 0 && setList.size() <= 0) {
            ToastUtils.showShort("请选择检验项目");
            return false;
        }
        return true;
    }

    // 请求预约时间列表
    private Disposable reqDatelList() {
        return APIRetrofit.getDefault().reqDateList2("time")
                .compose(RxUtil.<BaseResult2<List<OrderDate>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<OrderDate>>>() {
                    @Override
                    public void accept(BaseResult2<List<OrderDate>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        dateList = listBaseResult2.getData();
                        if (isDataEmpty(dateList)) {
                            OrderDate date = new OrderDate();
                            date.setScalar(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                            currOrderData = date;
                        } else {
                            dateList.get(0).setSelect(true);
                            currOrderData = dateList.get(0);
                        }
                        adapter.setDataList(dateList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 根据分类id请求项目分类
    private Disposable reqItemList(ItemType type) {
        return APIRetrofit.getDefault().reqItemList("0", type.getId())
                .compose(RxUtil.<BaseResult2<List<ItemSet>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ItemSet>>>() {
                    @Override
                    public void accept(BaseResult2<List<ItemSet>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            itemByTypeList = listBaseResult2.getData();
                            itemByTypeAdapter.setDataList(itemByTypeList);
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 请求常规项目
    private Disposable reqComItem() {
        return APIRetrofit.getDefault().reqComItemCategory("auth", "time")
                .compose(RxUtil.<BaseResult2<List<ItemSet>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ItemSet>>>() {
                    @Override
                    public void accept(BaseResult2<List<ItemSet>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        itemSetList = listBaseResult2.getData();
                        setSelectedItemListAndPrice();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 搜索,查询,项目
    private Disposable reqQueryItem(String name) {
        return APIRetrofit.getDefault().reqSearchItemList(name, "1")
                .compose(RxUtil.<BaseResult2<List<ItemSet>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ItemSet>>>() {
                    @Override
                    public void accept(BaseResult2<List<ItemSet>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            queryItemList = listBaseResult2.getData();
                            // 遍历已经选择的项目,设置查询出来的数据的选中状态
                            for (int i = 0; i < itemSetList.size(); i++) {
                                for (int j = 0; j < queryItemList.size(); j++) {
                                    if (TextUtils.equals(itemSetList.get(i).getName(), queryItemList.get(j).getName())) {
                                        queryItemList.get(j).setSelect(true);
                                    }
                                }
                            }
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                        queryItemAdapter.setDataList(queryItemList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("查询错误");
                    }
                });
    }

    // 搜索,查询,套餐
    private Disposable reqQuerySet(String name) {
        return APIRetrofit.getDefault().reqSearchItemList(name, "2")
                .compose(RxUtil.<BaseResult2<List<ItemSet>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ItemSet>>>() {
                    @Override
                    public void accept(BaseResult2<List<ItemSet>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            querySetList = listBaseResult2.getData();
                            // 遍历已经选择的项目,设置查询出来的数据的选中状态
                            for (int i = 0; i < setList.size(); i++) {
                                for (int j = 0; j < querySetList.size(); j++) {
                                    if (TextUtils.equals(setList.get(i).getName(), querySetList.get(j).getName())) {
                                        querySetList.get(j).setSelect(true);
                                    }
                                }
                            }
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                        querySetAdapter.setDataList(querySetList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("查询错误");
                    }
                });
    }

    private void setSelectedItemListAndPrice() {
        itemAdapter.setDataList(itemSetList);
        setAdapter.setDataList(setList);
        tv_price.setText("总价：¥" + getItemSetTotalPrice());
    }

    // 计算套餐总价格
    private String getItemSetTotalPrice() {
        BigDecimal total = new BigDecimal(0);
        if (itemSetList.size() <= 0 && setList.size() <= 0) {
            return total.doubleValue() + "";
        }
        for (int i = 0; i < itemSetList.size(); i++) {
            double temp = Double.parseDouble(itemSetList.get(i).getPrice());
            total = total.add(new BigDecimal(temp));
        }
        for (int i = 0; i < setList.size(); i++) {
            double temp = Double.parseDouble(setList.get(i).getPrice());
            total = total.add(new BigDecimal(temp));
        }

        return total.doubleValue() + "";
    }

    private class DateListAdapter extends ListBaseAdapter<OrderDate> {

        public DateListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_order_date_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            final TextView tv_date = holder.getView(R.id.tv_date);

            OrderDate date = mDataList.get(position);
            tv_date.setText(date.getTimeStrCn() + ":" + date.getTimeStr());// 自己生成的时间用这个
            tv_date.setText(date.getScalar());// 接口给的时间用这个

            if (date.isSelect()) {
                tv_date.setBackgroundResource(R.drawable.shape_blue_rad_13_5dp_bg);
                tv_date.setTextColor(getResources().getColor(R.color.white));
            } else {
                tv_date.setBackground(null);
                tv_date.setTextColor(getResources().getColor(R.color.text_dark_gray));
            }

            tv_date.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    currOrderData = dateList.get(position);
                    for (int i = 0; i < dateList.size(); i++) {
                        if (position == i) {
                            dateList.get(i).setSelect(true);
                        } else {
                            dateList.get(i).setSelect(false);
                        }
                        adapter.setDataList(dateList);
                    }
                }
            });
        }
    }

    // 选择的项目或套餐
    private class SelectedItemListAdapter extends ListBaseAdapter<ItemSet> {
        public int TYPE = 1;// 1 项目 2 套餐

        public SelectedItemListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_selected_item_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_price = holder.getView(R.id.tv_price);
            ImageView iv_del = holder.getView(R.id.iv_del);
            ImageView iv_tips = holder.getView(R.id.iv_tips);
            RecyclerView rcv_sub_item = holder.getView(R.id.rcv_sub_item);

            final ItemSet item = mDataList.get(position);

            tv_name.setText(item.getName());
            tv_time.setText(item.getDay() + "天");
            tv_price.setText("¥" + item.getPrice());
            iv_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TYPE == 1) {
                        itemSetList.remove(position);
                    } else {
                        setList.remove(position);
                    }
                    setSelectedItemListAndPrice();
                }
            });
            iv_tips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tv_content.setText(item.getSignificance());
//                    mCirclePop.showAtAnchorView(view, YGravity.ABOVE, XGravity.CENTER, 0, 0);
                    mCirclePop.showAsDropDown(view, -SizeUtils.dp2px(90), 0);
                }
            });

            SubItemListAdapter adapter = new SubItemListAdapter(getActivity());
            LinearLayoutManager manager = new LinearLayoutManager(getActivity());
            rcv_sub_item.setLayoutManager(manager);
            rcv_sub_item.setAdapter(adapter);
            adapter.setDataList(new ArrayList<ItemSet>());
        }
    }

    // 子项目adapter
    private class SubItemListAdapter extends ListBaseAdapter<ItemSet> {

        public SubItemListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return 0;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {

        }
    }

    // 按照名称检索项目名称adapter
    private class QueryItemListAdapter extends ListBaseAdapter<ItemSet> {
        public int TYPE = 1; // 1 项目 2 套餐

        public QueryItemListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_query_item_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            LinearLayout ll_item = holder.getView(R.id.ll_item);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_price = holder.getView(R.id.tv_price);
            TextView tv_check = holder.getView(R.id.tv_check);
            ImageView iv_tips = holder.getView(R.id.iv_tips);

            final ItemSet item = mDataList.get(position);
            tv_name.setText(item.getName());
            tv_price.setText("¥" + item.getPrice());
            if (item.isSelect()) {
                tv_check.setText("√");
            } else {
                tv_check.setText("");
            }

            ll_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (TYPE == 1) {
                        mDataList.get(position).setSelect(!item.isSelect());
                        queryItemAdapter.notifyDataSetChanged();
                    } else {
                        mDataList.get(position).setSelect(!item.isSelect());
                        querySetAdapter.notifyDataSetChanged();
                    }
                }
            });
            iv_tips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tv_content.setText(item.getSignificance());
                    mCirclePop.showAsDropDown(view, -SizeUtils.dp2px(90), 0);
                }
            });
        }
    }

    // 项目类型分类adapter
    private class ItemTypeAdapter extends ListBaseAdapter<ItemType> {

        public ItemTypeAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_item_type_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            RelativeLayout rl_type_name = holder.getView(R.id.rl_type_name);
            TextView tv_type_name = holder.getView(R.id.tv_type_name);
            ImageView iv_right_icon = holder.getView(R.id.iv_right_icon);
            RecyclerView rcv_item_by_type_list = holder.getView(R.id.rcv_item_by_type_list);

            final ItemType type = mDataList.get(position);
            tv_type_name.setText(type.getName());
            if (type.isSelect()) {
                iv_right_icon.setImageResource(R.mipmap.ai_sick_down_arrow);
                rcv_item_by_type_list.setVisibility(View.VISIBLE);
            } else {
                iv_right_icon.setImageResource(R.mipmap.ai_sick_right_arrow);
                rcv_item_by_type_list.setVisibility(View.GONE);
            }
            LinearLayoutManager manager = new LinearLayoutManager(getActivity());
            rcv_item_by_type_list.setLayoutManager(manager);
            rcv_item_by_type_list.setAdapter(itemByTypeAdapter);
            itemByTypeAdapter.setDataList(itemByTypeList);

            rl_type_name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < itemTypeList.size(); i++) {
                        if (i == position) {
                            itemTypeList.get(i).setSelect(true);
                        } else {
                            itemTypeList.get(i).setSelect(false);
                        }
                    }
                    itemTypeAdapter.setDataList(itemTypeList);
//                    hideProgress();
                    reqItemList(type);
//                    showProgress();
                }
            });
        }
    }

    // 按照项目分类检索项目列表adapter
    private class ItemByTypeListAdapter extends ListBaseAdapter<ItemSet> {

        public ItemByTypeListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_query_item_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            LinearLayout ll_item = holder.getView(R.id.ll_item);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_price = holder.getView(R.id.tv_price);
            TextView tv_check = holder.getView(R.id.tv_check);
            ImageView iv_tips = holder.getView(R.id.iv_tips);

            final ItemSet item = mDataList.get(position);
            tv_name.setText(item.getName());
            tv_price.setText("¥" + item.getPrice());
            if (item.isSelect()) {
                tv_check.setText("√");
            } else {
                tv_check.setText("");
            }

            ll_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDataList.get(position).setSelect(!item.isSelect());
                    itemByTypeAdapter.notifyDataSetChanged();
                }
            });
            iv_tips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tv_content.setText(item.getSignificance());
                    mCirclePop.showAsDropDown(view, -SizeUtils.dp2px(90), 0);
                }
            });
        }
    }

    // 收藏adapter
    private class CollectItemListAdapter extends ListBaseAdapter<ItemSet> {

        public CollectItemListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_query_item_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            LinearLayout ll_item = holder.getView(R.id.ll_item);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_price = holder.getView(R.id.tv_price);
            TextView tv_check = holder.getView(R.id.tv_check);
            ImageView iv_tips = holder.getView(R.id.iv_tips);

            final ItemSet item = mDataList.get(position);
            tv_name.setText(item.getName());
            tv_price.setText("¥" + item.getPrice());
            if (item.isSelect()) {
                tv_check.setText("√");
            } else {
                tv_check.setText("");
            }

            ll_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDataList.get(position).setSelect(!item.isSelect());
                    collectItemAdapter.notifyDataSetChanged();
                }
            });
            iv_tips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tv_content.setText(item.getSignificance());
                    mCirclePop.showAsDropDown(view, -SizeUtils.dp2px(90), 0);
                }
            });
        }
    }
}